<?php

namespace App\Service\System;

use App\DataStore\RedisGeneral;
use Gregwar\Captcha\CaptchaBuilder;


class CaptchaService
{
    public function getCaptcha(){
        // 创建验证码生成器
        $builder = new CaptchaBuilder();
        $builder->build(200, 80); // 设置验证码宽度和高度

        // 获取验证码内容
        $captchaCode = $builder->getPhrase();
        // 输出图像
        $imageData = $builder->getContents(); // 获取图像资源
        ob_start();
        imagejpeg($imageData);
        $image = ob_get_contents();
        ob_end_clean();
        // 将图像数据转换为 Base64 编码
        $base64Image = base64_encode($image);
        // 构建 Base64 数据 URL
        $dataUrl = 'data:image/jpeg;base64,' . $base64Image;
        // 存好redis
        $key = md5Str();
        RedisGeneral::getInc()->setCaptchaRedis($key,[
            'captcha' => $captchaCode
        ]);
        return [
            'key' => $key,
            'base64_captcha' => $dataUrl
        ];
    }

    public function checkCaptcha($key,$captcha){
        $redisCaptcha = jsonDecode(RedisGeneral::getInc()->getCaptchaRedis($key));
        if(empty($redisCaptcha)){
            apiError("验证码错误");
        }
        if($redisCaptcha['captcha']!=$captcha){
            apiError("验证码错误");
        }
    }

}